package com.rxt.controller;


import com.rxt.common.result.Result;
import com.rxt.service.FileStorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 周梓文
 * @since 2023-08-24
 */
@Api(tags = "文件上传")
@Slf4j
@RestController
@RequestMapping
public class UploadController {

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {

        //file是一个临时文件，需要转存，不然本次请求之后会销毁
        log.info(file.toString());

        //原始文件名字
        String originalFileName = file.getOriginalFilename();
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID() + suffix;

        //上传图片到图片服务器，降低自生应用服务器的带宽消耗
        InputStream fis = null;
        try {
            fis = file.getInputStream();
            // TODO 文件上传
            String filePath = fileStorageService.uploadImgFile("", fileName, fis);
            System.out.println(filePath);
            //上传成功  则返回文件的路径
            return Result.ok(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                assert fis != null;
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        //上传失败  范围错误码
        return Result.fail("图片上传失败");
    }
}
